using MediatR;
using Microsoft.AspNetCore.Mvc;
using S.M.SmartMedical.API.Read.Application.Query;
using S.M.SmartMedical.Domain.Enums;
using S.M.SmartMedical.ErrorCode;

namespace S.M.SmartMedical.API.Read.Controllers;

/// <summary>
/// 医疗项目控制器
/// </summary>
[ApiController]
[Route("api/[controller]")]
public class MedicalProjectController : ControllerBase
{
    private readonly IMediator _mediator;
    private readonly ILogger<MedicalProjectController> _logger;

    public MedicalProjectController(IMediator mediator, ILogger<MedicalProjectController> logger)
    {
        _mediator = mediator;
        _logger = logger;
    }

    /// <summary>
    /// 获取指定院区的医疗项目列表
    /// </summary>
    /// <param name="hospitalAreaId">院区ID</param>
    /// <param name="category">项目类别（可选）：0-检验项目，1-检查项目</param>
    /// <param name="searchKeyword">搜索关键词（可选）</param>
    /// <param name="onlyEnabled">是否只返回启用的项目，默认为true</param>
    /// <returns>医疗项目列表</returns>
    [HttpGet]
    [ProducesResponseType(typeof(APIResult<List<MedicalProjectDto>>), 200)]
    public async Task<ActionResult<APIResult<List<MedicalProjectDto>>>> GetMedicalProjects(
        [FromQuery] int hospitalAreaId,
        [FromQuery] ProjectCategory? category = null,
        [FromQuery] string? searchKeyword = null,
        [FromQuery] bool onlyEnabled = true)
    {
        try
        {
            _logger.LogInformation("接收到获取医疗项目列表请求，院区ID：{HospitalAreaId}，类别：{Category}，搜索关键词：{SearchKeyword}", 
                hospitalAreaId, category, searchKeyword);

            var query = new GetMedicalProjectsQuery
            {
                HospitalAreaId = hospitalAreaId,
                Category = category,
                SearchKeyword = searchKeyword,
                OnlyEnabled = onlyEnabled
            };

            var result = await _mediator.Send(query);

            _logger.LogInformation("获取医疗项目列表成功，返回{Count}个项目", result.Data?.Count ?? 0);

            return Ok(result);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取医疗项目列表时发生异常，院区ID：{HospitalAreaId}", hospitalAreaId);
            
            return Ok(new APIResult<List<MedicalProjectDto>>
            {
                Code = APIEnum.Fail,
                Message = $"获取医疗项目列表失败：{ex.Message}",
                Data = new List<MedicalProjectDto>()
            });
        }
    }

    /// <summary>
    /// 根据项目类别获取医疗项目列表
    /// </summary>
    /// <param name="hospitalAreaId">院区ID</param>
    /// <param name="category">项目类别：0-检验项目，1-检查项目</param>
    /// <param name="searchKeyword">搜索关键词（可选）</param>
    /// <returns>医疗项目列表</returns>
    [HttpGet("by-category")]
    [ProducesResponseType(typeof(APIResult<List<MedicalProjectDto>>), 200)]
    public async Task<ActionResult<APIResult<List<MedicalProjectDto>>>> GetMedicalProjectsByCategory(
        [FromQuery] int hospitalAreaId,
        [FromQuery] ProjectCategory category,
        [FromQuery] string? searchKeyword = null)
    {
        try
        {
            _logger.LogInformation("接收到按类别获取医疗项目列表请求，院区ID：{HospitalAreaId}，类别：{Category}，搜索关键词：{SearchKeyword}", 
                hospitalAreaId, category, searchKeyword);

            var query = new GetMedicalProjectsQuery
            {
                HospitalAreaId = hospitalAreaId,
                Category = category,
                SearchKeyword = searchKeyword,
                OnlyEnabled = true
            };

            var result = await _mediator.Send(query);

            _logger.LogInformation("按类别获取医疗项目列表成功，返回{Count}个项目", result.Data?.Count ?? 0);

            return Ok(result);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "按类别获取医疗项目列表时发生异常，院区ID：{HospitalAreaId}，类别：{Category}", hospitalAreaId, category);
            
            return Ok(new APIResult<List<MedicalProjectDto>>
            {
                Code = APIEnum.Fail,
                Message = $"获取医疗项目列表失败：{ex.Message}",
                Data = new List<MedicalProjectDto>()
            });
        }
    }
}